package cn.javase.concurrent._设计模式._同步模式之保护性暂停;

import lombok.extern.slf4j.Slf4j;

/**
 * 带超时版的GuardedObject
 */
@Slf4j
public class GuardedObjectV2 {

    private Object response;                    // 结果

    // 获取
    public Object get(long millis) {
        synchronized (this) {
            // 1. 记录最初时间
            long begin = System.currentTimeMillis();
            // 2. 已经经历的时间
            long timePassed = 0;
            while (response == null) {
                // 3. 还要等待的时间
                long waitTime = millis - timePassed;
                if (waitTime <= 0) {
                    log.debug("break...");
                    break;
                }
                try {
                    this.wait(waitTime);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                // 4. 更新经历的时间
                timePassed = System.currentTimeMillis() - begin;
            }
            return response;
        }
    }

    // 设置并唤醒
    public void complete(Object response) {
        synchronized (this) {
            this.response = response;
            this.notifyAll();
        }
    }

}
